import { computed, ref, type ComputedRef } from 'vue'
import { defineStore } from 'pinia'
import type { TokenInfo } from '@/api/login/types'

export const useTokenStore = defineStore('tokenStore', () => {
    const tokenInfo = ref<TokenInfo>({
        token: '',
        username: ''
    })
    const USERNAME: ComputedRef<string> = computed(() => tokenInfo.value.username)

    const TOKEN: ComputedRef<string> = computed(() => tokenInfo.value.token)
    /* 设置token,登录成功后调用 */ 
    const setToken = (token: TokenInfo) => {
        tokenInfo.value = token
    }
    /* 清除token,退出登录后调用 */
    const clear = () => {
        tokenInfo.value = {
            token: '',
            username: ''
        }
    }
    return {tokenInfo, USERNAME, TOKEN, setToken, clear}
}, {
    persist: {
        key: 'token-key',
        storage: sessionStorage
    }
})